﻿
var type = "";
var typeName = "";
//var cityId = "";
$(function () {
    initTree();
    initTable();
});
var $table = $('#table');
var $tree = $('#tree');
function initTree() {
    $tree.jstree({
        'core': {
            'data': {
                'type': 'post',
                "url": "/AdministrativeDivision/TreeExcludeStreetAsync",
                "dataType": "json"
            }
        }
    });
    $tree.on("changed.jstree", function (e, data) {
        console.log(data);

        if (data.action == "ready" || data.node.parent == "#") {
            type = "";
            typeName = "";
        } else {
            typeName = data.node.text;
            type = data.selected[0];
        }

        //cityId = data.node.parent;

        console.log(type);
        refreshTable();
    });
}
function initTable() {

    $table.bootstrapTable({
        url: '/PartialArea/IndexAsync',            //数据来源地址
        method: 'post',                     //数据请求方式
        striped: true,                      //是否显示行间隔色
        cache: false,                       //是否使用缓存，默认为true，所以一般情况下需要设置一下这个属性（*）
        pagination: true,                   //是否启用分页
        sidePagination: 'server',           //在服务器端分页
        queryParams: queryParams,           //传递参数
        pageNumber: 1,                      //初始化加载第一页，默认第一页
        pageSize: 20,                       //每页的记录行数（*）
        pageList: [10, 20, 30, 40, 50],     //可供选择的每页的行数（*）
        clickToSelect: true,                //是否启用点击选中行
        //toolbar: "#tableToolBar",
        height: getHeight(),
        columns: [{
            //    width: 38,
            //    field: 'selected',
            //    checkbox: true,
            //}, {
            title: '行号',
            align: 'center',
            formatter: function (value, row, index) { return index + 1; }
        }, {
            field: 'id',
            title: '编码',
            align: 'center',
        }, {
            //    field: 'name',
            //    title: '名称',
            //    align: 'center'
            //}, {
            field: 'areaName',
            title: '所属区域',
            align: 'center',
        }, {
            field: 'name',
            title: '片区',
            align: 'center',
        }, {
            title: '可选操作',
            align: 'center',
            events: operateEvents,
            formatter: operateFormatter
        }]
        //Type, Grade, Level, CityId, AreaId, Address
    });
}

//查询的参数
var queryParams = function (params) {
    var temp = {
        pageSize: params.limit,                             //行数
        pageIndex: (params.offset / params.limit) + 1,      //页码
        search: $('#searchKey').val(),                       //查询内容
        type: type
    };
    console.log(temp);
    return temp;
};

//刷新表格数据
var refreshTable = function () {
    $table.bootstrapTable('refresh');
}

//自定义的列事件
function operateFormatter(value, row, index) {
    var txt = new Array();
    var str = $('#options').val().split(',');

    var svc = $.parseJSON($('#depart_a').val());
    if (svc != null) {//初始化时，获取到的数据
        for (var i = 0; i < str.length; i++) {
            txt.push('<label for="authority_' + index + '_' + i + '" style="margin-right:15px">' +
                '<input class="req" type="checkbox" value="' + i + '" ' + (isContains(svc, row.areaId, row.id, i + '') ? "Checked" : "") + ' name="authority_' + index + '" id="authority_' + index + '_' + i + '"/>' + str[i] + '</label>');
        }
        return txt.join(' ');
    } else
        //console.log(svc);
        $.ajax({
            url: "/Department/GetDepartAuthority",
            type: "post",
            dataType: "json",
            async: false,
            data: { departId: $('#depart_id').val(), areaId: row.areaId, strId: row.id },
            success: function (data) {
                //Info,Success,Warning,Error
                var type = data.type;
                if (type == 1) {

                    for (var i = 0; i < str.length; i++) {
                        txt.push('<label for="authority_' + index + '_' + i + '" style="margin-right:15px">' +
                            '<input class="req" type="checkbox" value="' + i + '" ' + (isContains(data.data, row.areaId, row.id, i + '') ? "Checked" : "") + ' name="authority_' + index + '" id="authority_' + index + '_' + i + '"/>' + str[i] + '</label>');
                    }
                } else {
                    //svc = data.data;
                    for (var i = 0; i < str.length; i++) {
                        txt.push('<label for="authority_' + index + '_' + i + '" style="margin-right:15px">' +
                            '<input class="req" type="checkbox" value="' + i + '" name="authority_' + index + '" id="authority_' + index + '_' + i + '"/>' + str[i] + '</label>');
                    }
                }

                return txt.join(' ');
                console.log(data.data);
            }
        });


    //return [
    //    '<a class="edit" href="javascript:void(0)" title="编辑">',
    //    '<i class="glyphicon glyphicon-edit"></i>',
    //    '</a>  ',
    //    '<a class="remove" href="javascript:void(0)" title="删除">',
    //    '<i class="glyphicon glyphicon-remove"></i>',
    //    '</a>'
    //].join('');
}

window.operateEvents = {
    'click .req': function (e, value, row, index) {
        //console.log($.param(row) + "|" + index + "|" + $('input[name="authority_' + index + '"]').val());
        var chk_auth = "";
        $('input[name="authority_' + index + '"]:checked').each(function () {
            chk_auth += "," + $(this).val();
        });

        $.ajax({
            url: "/Department/DepartAuthorityAsync",
            type: "post",
            dataType: "json",
            data: { jstr: $.param(row), chkVal: chk_auth.substring(1), departId: $('#depart_id').val() },
            success: function (data) {
                //Info,Success,Warning,Error
                var type = data.type;
                if (type == 1) {
                    layer.msg(data.content,
                        {
                            icon: 6, time: 2000
                        });
                } else {
                    layer.msg(data.content, { icon: 5, time: 2000 });
                }
            }
        });
    },
    'click .remove': function (e, value, row, index) {

    }
};


function isTrueFormatter(value, row, index) {
    return value ? '<i class="glyphicon glyphicon-ok"></i>' : '<i class="glyphicon glyphicon-remove"></i>'
}

//获取表格高度
function getHeight() {
    return $(window).height() - 150;
}
function isContains(str, area, sid, substr3) {

    if (str.Exists("['AreaId']=='" + area + "'" && "['Id']=='" + sid + "'")) {
        var _txt = str.First("['AreaId']=='" + area + "'" && "['Id']=='" + sid + "'").Name;
        var reg = new RegExp(substr3);//是否包含的字符串
        return reg.test(_txt);
    } else {
        return false;
    }

}

//重置表格高度
setTimeout(function () {
    $table.bootstrapTable('resetView');
}, 200);

//重置表格高度
$(window).resize(function () {
    $table.bootstrapTable('resetView', {
        height: getHeight()
    });
});

////刷新按钮
//$('#refreshBtn').click(function (e) {
//    $table.bootstrapTable('refresh');
//});

////搜索按钮
//$('#searchBtn').click(function (e) {
//    $table.bootstrapTable('refresh');
//});

////插入按钮
//$('#insertBtn').click(function (e) {
//    if (type == "") {
//        layer.msg("请选择指定区域！", { icon: 5, time: 2000 });
//        return;
//    }
//    parent.layer.open({
//        type: 2,
//        title: '添加参数',
//        shadeClose: false,
//        shade: 0.4,
//        area: ['800px', '480px'],
//        content: '/SchoolArea/Insert?type=' + type + "&typeName=" + typeName,// + "&parentId=" + cityId,
//        end: function () {
//            refreshTable();
//        }
//    });
//});

////编辑按钮
//$('#editBtn').click(function (e) {
//    var selected = $table.bootstrapTable('getSelections');

//    if (selected.length > 1) {
//        layer.msg("一次只能修改一条数据！", { icon: 5, time: 2000 });
//        return;
//    }

//    if (selected.length == 0) {
//        layer.msg("请选择您要修改的数据！", { icon: 5, time: 2000 });
//        return;
//    }
//    editData(selected[0].id);
//});

////打开编辑窗口
//function editData(id) {
//    parent.layer.open({
//        type: 2,
//        title: '修改参数',
//        shadeClose: true,
//        shade: 0.4,
//        area: ['800px', '480px'],
//        content: '/SchoolArea/Edit?id=' + id,
//        end: function () {
//            refreshTable();
//        }
//    });
//}

////删除按钮
//$('#deleteBtn').click(function (e) {
//    var selected = $table.bootstrapTable('getSelections');
//    if (selected.length == 0) {
//        layer.msg("请选择您要删除的数据！", { icon: 5, time: 2000 });
//        return;
//    }

//    var arr = [];
//    for (var i = 0; i < selected.length; i++) {
//        arr.push(selected[i].id);
//    }

//    var ids = arr.join(",");

//    layer.confirm('您确定要删除所选数据吗', {
//        btn: ['是的', '取消'] //按钮
//    }, function () {
//        $.ajax({
//            url: "/SchoolArea/DeleteAsync",
//            type: "post",
//            dataType: "json",
//            data: { ids: ids },
//            success: function (data) {
//                //Info,Success,Warning,Error
//                var type = data.type;
//                if (type == 1) {
//                    layer.msg(data.content,
//                        {
//                            icon: 6, time: 2000
//                        },
//                        function () {
//                            refreshTable();
//                        });
//                } else {
//                    layer.msg(data.content, { icon: 5, time: 2000 });
//                }
//            }
//        });
//    }, function () {
//        return;
//    });


//});


//----------------------------------------
function itemParser(str) {
    var result;

    result = str.replace(/item/gi, "");
    result = result.replace(/\[/g, "item[");

    return result;
}
//Extend Array with prototype

Array.prototype.Count = function (expr) {
    if (expr == null || expr == "") return this.length;

    return ($.grep(this, function (item, index) {
        return (eval(itemParser(expr)));
    }).length);
};


Array.prototype.First = function (expr) {
    if (expr == null || expr == "") expr = "true";

    var result = ($.grep(this, function (item, index) {
        return (eval(itemParser(expr)));
    }));

    return (result.length > 0 ? result[0] : null);
};


Array.prototype.Exists = function (expr) {
    if (expr == null || expr == "") expr = true;

    var result = ($.grep(this, function (item, index) {
        return (eval(itemParser(expr)));
    }));

    return (result.length > 0);
};


Array.prototype.Where = function (expr) {
    return ($.grep(this, function (item, index) {
        return (eval(itemParser(expr)));
    }));
};
